const { generateToken } = require("../utils/jwt");
const axios = require("axios");
const querystring = require("querystring");
const https = require("https");
const Visitor = require("../models/Visitor");
const { v4: uuidv4 } = require("uuid");
const { processImageUrl } = require("../utils/imageUtils");
const { sequelize } = require("../config/database");
const TokenTransaction = require("../models/TokenTransaction");
const UserBenefit = require("../models/UserBenefit");

// 自定义域名配置
const CUSTOM_DOMAIN = "https://www.know1.ai";

// 代理配置
const USE_PROXY = process.env.USE_PROXY === "true";
const PROXY_CONFIG = USE_PROXY
  ? {
      protocol: process.env.PROXY_PROTOCOL || "http",
      host: process.env.PROXY_HOST || "127.0.0.1",
      port: parseInt(process.env.PROXY_PORT || "10792"),
    }
  : null;

// 创建自定义HTTPS代理
const httpsAgent = new https.Agent({
  minVersion: "TLSv1.2",
  maxVersion: "TLSv1.3",
  rejectUnauthorized: true,
  timeout: 10000,
});

https.globalAgent.options.ciphers = [
  "TLS_AES_256_GCM_SHA384",
  "TLS_CHACHA20_POLY1305_SHA256",
  "TLS_AES_128_GCM_SHA256",
  "ECDHE-RSA-AES128-GCM-SHA256",
].join(":");

/**
 * 获取Google登录的URL
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
exports.getGoogleAuthUrl = (req, res) => {
  try {
    // const googleAuthUrl = "http://127.0.0.1:3000/auth/google";
    const googleAuthUrl = "https://api.knomi.me/auth/google";
    return res.status(200).json({
      success: true,
      data: {
        googleAuthUrl,
      },
    });
  } catch (error) {
    console.error("获取Google登录URL错误:", error);
    return res.status(500).json({
      success: false,
      message: "服务器内部错误",
      error: process.env.NODE_ENV === "development" ? error.message : undefined,
    });
  }
};

/**
 * 使用授权码交换获取Access Token和Refresh Token
 * @param {string} code - 授权码
 * @returns {Promise<Object>} - 包含access_token和refresh_token的对象
 */
async function exchangeCodeForTokens(code) {
  try {
    const requestConfig = {
      headers: {
        "Content-Type": "application/x-www-form-urlencoded",
      },
      httpsAgent: new https.Agent({
        secureProtocol: "TLSv1_2_method", // 强制 TLS 1.2
      }),
      timeout: 10000,
    };

    // 如果启用了代理，添加代理配置
    if (USE_PROXY) {
      requestConfig.proxy = PROXY_CONFIG;
    }

    const response = await axios.post(
      "https://oauth2.googleapis.com/token",
      new URLSearchParams({
        grant_type: "authorization_code",
        code: code,
        client_id:
          "908489240251-29g9tv65es25mqiq7e78n99duipc808a.apps.googleusercontent.com",
          // "983569305662-lv5vpe43ppdh83fj5fje802rj4kr5ias.apps.googleusercontent.com",
        client_secret: "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",
        // client_secret: "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",
        // redirect_uri: "http://127.0.0.1:3000/auth/google/callback",
        redirect_uri: "https://api.know1.ai/auth/google/callback",
      }),
      requestConfig
    );
    return {
      access_token: response.data.access_token,
      refresh_token: response.data.refresh_token,
      expires_in: response.data.expires_in,
      id_token: response.data.id_token,
    };
  } catch (error) {
    console.error("交换失败1:", error);
    throw new Error("授权码交换失败");
  }
}
/**
 * 使用access_token获取用户信息
 * @param {string} accessToken - 访问令牌
 * @returns {Promise<Object>} - 用户信息
 */
async function getUserInfo(accessToken) {
  try {
    const requestConfig = {
      headers: {
        Authorization: `Bearer ${accessToken}`,
      },
      httpsAgent: new https.Agent({
        secureProtocol: "TLSv1_2_method", // 强制 TLS 1.2
      }),
      timeout: 10000,
    };

    // 如果启用了代理，添加代理配置
    if (USE_PROXY) {
      requestConfig.proxy = PROXY_CONFIG;
    }

    const response = await axios.get(
      "https://www.googleapis.com/oauth2/v2/userinfo",
      requestConfig
    );
    console.log("【用户信息】获取成功:", response.data.picture);
    return response.data;
  } catch (error) {
    console.error(
      "【用户信息】获取失败:",
      error.response?.data || error.message
    );
    throw new Error("获取用户信息失败");
  }
}

/**
 * 检查URL是否来自我们的自定义域名
 * @param {string} url - 要检查的URL
 * @returns {boolean} - 是否来自自定义域名
 */
function isCustomDomainUrl(url) {
  return url && url.includes("www.know1.ai");
}

/**
 * 处理Google OAuth登录成功回调
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
exports.googleCallback = async (req, res) => {
  const transaction = await sequelize.transaction();
  
  try {
    // 获取授权码
    const authorizationCode = req.query.code;
    let userInfo;
    let visitor = req.user;
    let isFirstLogin = false;

    if (!visitor && authorizationCode) {
      // Passport认证失败或被跳过，使用授权码获取令牌
      const tokens = await exchangeCodeForTokens(authorizationCode);
      // 使用access_token获取用户信息
      if (tokens.access_token) {
        userInfo = await getUserInfo(tokens.access_token);
        try {
          // 查找是否存在访客用户
          let existingVisitor = await Visitor.findOne({
            where: { googleId: userInfo.id },
            transaction
          });

          if (existingVisitor) {
            // 用户存在，判断是否需要更新头像
            const needUpdateAvatar =
              !existingVisitor.avatar ||
              !isCustomDomainUrl(existingVisitor.avatar);

            // 只有在头像不存在或不是自定义域名时才处理头像
            let ossAvatarUrl = existingVisitor.avatar;
            if (needUpdateAvatar) {
              ossAvatarUrl = await processImageUrl(userInfo.picture);
            }

            // 更新登录信息
            existingVisitor.last_login = new Date();
            existingVisitor.login_count = existingVisitor.login_count + 1;
            existingVisitor.displayName = userInfo.name;

            // 只有在需要时才更新头像
            if (needUpdateAvatar) {
              existingVisitor.avatar = ossAvatarUrl;
            }

            await existingVisitor.save({ transaction });
            visitor = existingVisitor;
          } else {
            // 新用户，需要处理头像
            const ossAvatarUrl = await processImageUrl(userInfo.picture);

            // 创建新用户，并添加初始token
            visitor = await Visitor.create({
              uuid: uuidv4(),
              googleId: userInfo.id,
              email: userInfo.email,
              displayName: userInfo.name,
              avatar: ossAvatarUrl,
              last_login: new Date(),
              login_count: 1,
              status: "active",
              tokens_balance: 200, // 初始赠送200个token
              tokens_promotional: 200, // 记录到促销代币余额
            }, { transaction });

            // 创建或更新用户权益记录
            let userBenefit = await UserBenefit.findOne({
              where: { user_uuid: visitor.uuid },
              transaction,
            });

            if (!userBenefit) {
              userBenefit = await UserBenefit.create(
                {
                  user_uuid: visitor.uuid,
                },
                { transaction }
              );
            }

            // 记录代币交易
            await TokenTransaction.create(
              {
                user_uuid: visitor.uuid,
                type: "promotional_grant",
                amount: 200,
                balance_after: 200,
                description: "新用户注册赠送代币",
                token_source: "promotional",
                status: "confirmed",
                server_type: "promotional",
                payment_order_id: uuidv4(),
              },
              { transaction }
            );
            
            // 标记为首次登录
            isFirstLogin = true;
          }
        } catch (dbError) {
          console.error("【Google回调】数据库操作错误:", dbError);
          await transaction.rollback();
          throw new Error("用户数据保存失败");
        }
      }
    }

    if (!visitor) {
      await transaction.rollback();
      throw new Error("无法获取用户信息");
    }

    await transaction.commit();

    const token = generateToken({
      uuid: visitor.uuid,
      type: "visitor",
      avatar: visitor.avatar,
      displayName: visitor.displayName,
      email: visitor.email,
      membership_tier: visitor.membership_tier,
      isFirstLogin: isFirstLogin,  // 添加首次登录标识
    });
    
    // 构建重定向URL，如果是首次登录则添加参数
    let redirectUrl = `https://www.know1.ai/#/?token=${token}`;
    if (isFirstLogin) {
      redirectUrl += "&isFirstLogin=true&tokens_balance=200";
    }
    
    // 重定向到前端的回调页面，附带token
    res.redirect(redirectUrl);
  } catch (error) {
    console.error("【Google回调】处理失败，错误详情:", error);
    
    // 如果事务还没有提交或回滚，则回滚
    try {
      await transaction.rollback();
    } catch (rollbackError) {
      console.error("【Google回调】事务回滚失败:", rollbackError);
    }
    
    // const errorRedirect = `http://localhost:5173/test/#/login?error=true`;
    const errorRedirect = `https://www.know1.ai/#/error=true`;
    console.log("【Google回调】重定向到错误页面:", errorRedirect);
    res.redirect(errorRedirect);
  }
};
